var WebSocket = window.WebSocket || window.MozWebSocket;
//Chat object
function chat_client(){
    this.ws //websocket object

    this.host = "virtualworld.com"
    this.port = 13001

    this.pub_id = null
    this.nickname = null
    this.email = null

    this.onChromeError=true
}


chat_client.prototype = {
    _init:function(){
        chat.ws = new WebSocket("ws://"+chat.host+":"+chat.port);

        //Connection state
        chat.ws.onopen = function(e) {
            chat.onChromeError=false
            document.getElementById('intro').style.display="block";
            document.getElementById('ws_icon').setAttribute('class',"connected");
            document.getElementById('ws_sentence').innerHTML = "Vous êtes connecté au serveur";
            setTimeout(chat._get_pub_ID, 50);
        };
        chat.ws.onclose = function(e) {
            chat._quit_chat(e.data);
        };
        chat.ws.onerror = function(e) {
            document.getElementById('error').style.display="block";
            document.getElementById('ws_icon').setAttribute('class',"not_connected");
            document.getElementById('ws_sentence').innerHTML = "Connection impossible";
        };

        //Message
        chat.ws.onmessage = function(e) {
            chat._receive_msg(e.data);
        };

        //Chrome dont detect error where connexion refused
        setTimeout(chat._chrome_error_handlers,1500);
    },

    _chrome_error_handlers:function(startTime){
        if(chat.onChromeError){
            document.getElementById('error').style.display="block";
            document.getElementById('ws_icon').setAttribute('class',"not_connected");
            document.getElementById('ws_sentence').innerHTML = "Connection impossible";
        }
    },

    _keyup_event:function(event){
        if(event.keyCode == 13){
            chat._send_msg();
        }
    },

    _get_pub_ID:function(){
        if (chat.pub_id == null) {
            var json = {"HELO":"want my pub_id plz"};
            chat.ws.send(JSON.stringify(json));
            setTimeout(chat._get_pub_ID, 500);
        }
    },

    _connect:function(){
        var nickname = document.getElementById('nickname').value;
        if(document.getElementById('password').value != ""){
            var password = document.getElementById('password').value
            var str = {
                "CONU" : {
                    "PUB_ID" : chat.pub_id,
                    "NICKNAME" : nickname,
                    "PASSWORD" : password
                }
            };
        }else{
            var str = {
                "CONU" : {
                    "PUB_ID" : chat.pub_id,
                    "NICKNAME" : nickname
                }
            };
        }

        chat.ws.send(JSON.stringify(str));
    },

    _send_msg:function(){
        var send_msg = document.getElementById('chat_input').value;
        document.getElementById('chat_input').value = "";
        var str = {
            "SEND" : {
                "PUB_ID" : chat.pub_id,
                "TEXT" : encodeURI(send_msg)
            }
        };
        chat.ws.send(JSON.stringify(str));
    },

    _get_infos:function(){
        var str = {
            "INFO" : {
                "PUB_ID" : chat.pub_id
            }
        };
        chat.ws.send(JSON.stringify(str));
    },

    _receive_msg:function(data){
        var jsonMsg = JSON.parse( data );
        console.log(jsonMsg);
        for(var i in jsonMsg){
            switch (i){
                case "WLCM": //welcome message + pub_id
                    chat.pub_id = jsonMsg[i].PUB_ID;
                    chat.motd = jsonMsg[i].MOTD;
                    break;

                //PING et LATENCY
                case "PING":
                    var str = '{"PONG":"'+jsonMsg[i]+'"}';
                    chat.ws.send_string(str);
                    break;

                case "LATENCY":
                    var latency = jsonMsg[i];
                    document.getElementById('ws_ping').innerHTML = latency+"ms";
                    if(parseInt(latency)>=200){
                        document.getElementById('ws_status').setAttribute('class',"no-signal");
                    }else if(parseInt(latency)>=100 && parseInt(latency)<200){
                        document.getElementById('ws_status').setAttribute('class',"low");
                    }else if(parseInt(latency)>=50 && parseInt(latency)<100){
                        document.getElementById('ws_status').setAttribute('class',"medium");
                    }else if(parseInt(latency)>=25 && parseInt(latency)<50){
                        document.getElementById('ws_status').setAttribute('class',"good");
                    }else if(parseInt(latency)>=0 && parseInt(latency)<25){
                        document.getElementById('ws_status').setAttribute('class',"excellent");
                    }
                    break;

                case "CONN":
                    switch(jsonMsg[i]["REPLY"]){
                        case "OK":
                            //chat.pub_id = jsonMsg[i].PUB_ID;
                            document.getElementById('intro').style.display = "none";
                            document.getElementById('chat').style.display = "block";
                            break;
                        case "NOK":
                            chat._connect_message("Connection impossible au chat");
                            break;
                        case "NPWD":
                            chat._connect_message("Utilisateur enregistré, indiquez le mot de passe");
                            break;
                        case "WPWD":
                            chat._connect_message("Mauvais mot de passe");
                            break;
                    }
                    break;

                case "MESG":
                    chat._message(jsonMsg[i].FROM, decodeURI(jsonMsg[i].TEXT));
                    break;

                case "INFO":
                    chat._message("Infos", jsonMsg[i].USERS_COUNT+" connectés");
                    break;

                case "UINF":
                    chat._sys_message(decodeURI(jsonMsg[i].TEXT));
                    break;

                case "ULST":
                    document.getElementById('ul_content').innerHTML = "";
                    for(var j=0;j<jsonMsg[i].UL.length;j++){
                        document.getElementById('ul_content').innerHTML += '<div class="user sex_'+jsonMsg[i].UL[j].SEXE+'">'+jsonMsg[i].UL[j].NICKNAME+'</div>';
                    }
                    break;
            }
            break;
        }
    },

    _quit_chat:function(){
        var str = {
            "QUIT" : {
                "PUB_ID" : chat.pub_id,
                "REASON" : "User quit."
            }
        };
        chat.ws.send(JSON.stringify(str));
        if (chat.ws) {
            chat.ws.close();
        }
    },

    _connect_message:function(str){
        document.getElementById('connect_error').innerHTML = str;
        document.getElementById('connect_error').style.opacity= 1
        setTimeout(function(){
            chat._erase_connect_message(0,2000);
        },2000)
    },

    _erase_connect_message:function(actual,delay){
        if(actual != 0)
            document.getElementById('connect_error').style.opacity= (1-(actual/delay))
        else
            document.getElementById('connect_error').style.opacity= 1

        if(actual<delay){
            var newValue = actual+100;
            setTimeout(function(){
                chat._erase_connect_message(newValue,delay);
            },100)
        }
    },

    _message:function(from, str){
        cell = document.getElementById('messages');
        cell.innerHTML += "<b>"+from + ":</b> " + str + "<br/>";
        cell.scrollTop = cell.scrollHeight;
    },

    _sys_message:function(str){
        cell = document.getElementById('messages');
        cell.innerHTML += "<b>"+str+"</b><br/>";
        cell.scrollTop = cell.scrollHeight;
    }


}

//Init chat
var chat;
window.onload = function() {
    chat = new chat_client();
    chat._init();
}